package com.jzo2o.market.handler;

import com.jzo2o.market.enums.ActivityStatusEnum;
import com.jzo2o.market.enums.CouponStatusEnum;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.task.SyncMessageHandleTask;
import com.jzo2o.redis.sync.SyncManager;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
@Component
@Slf4j
public class XxlJobHandler {

    @Resource
    private SyncManager syncManager;

    @Resource
    private IActivityService activityService;

    @Resource
    private ICouponService couponService;

    /**
     * 活动状态修改，
     * 1.活动进行中状态修改
     * 2.活动已失效状态修改
     * 1分钟一次
     */
    @XxlJob("updateActivityStatus")
    public void updateActivitySatus() {
        log.info("开始执行活动状态修改任务");
        //到达活动开始时间将状态改为进行中
        boolean update = activityService.lambdaUpdate()
                .eq(Activity::getStatus, ActivityStatusEnum.NO_DISTRIBUTE.getStatus())
                .le(Activity::getDistributeStartTime, LocalDateTime.now())
                .ge(Activity::getDistributeEndTime, LocalDateTime.now())
                .set(Activity::getStatus, ActivityStatusEnum.DISTRIBUTING.getStatus())
                .update();

        //查询到达活动结束时间的活动并修改状态为已失效
        activityService.lambdaUpdate()
                .eq(Activity::getStatus, ActivityStatusEnum.DISTRIBUTING.getStatus())
                .le(Activity::getDistributeEndTime, LocalDateTime.now())
                .set(Activity::getStatus, ActivityStatusEnum.LOSE_EFFICACY.getStatus())
                .update();

    }

    /**
     * 已领取优惠券自动过期任务
     */
    @XxlJob("processExpireCoupon")
    public void processExpireCoupon() {
        log.info("开始执行优惠券过期任务");
        couponService.lambdaUpdate()
                .eq(Coupon::getStatus, CouponStatusEnum.NO_USE.getStatus())
                .le(Coupon::getValidityTime, LocalDateTime.now())
                .set(Coupon::getStatus, CouponStatusEnum.INVALID.getStatus())
                .update();
    }

    /**
     * 抢券活动列表和活动库存预热定时任务
     */
    @XxlJob("activityPreheat")
    public void AcitivityPreheat() {
        log.info("开始抢券活动列表和活动库存预热定时任务");
        try {
            activityService.Preheat();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Autowired
    private SyncMessageHandleTask task;
    /**
     * 抢券结果同步定时任务
     */
    @XxlJob("seizeCouponSyncJob")
    public void seizeCouponSyncJob() {
        log.info("抢券结果同步定时任务");
        try {
            for (Long i = 0L; i < 10; i++) {
                task.batchHandleSyncMessage(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
